package cn.edu.hit.kg;

import net.sf.json.JSONObject;
import org.neo4j.driver.v1.*;

import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author Wang 2016年12月12日
 * neo驱动
 */

public class NeoDriver implements AutoCloseable {
    static String url = "bolt://localhost";
    static String username = "neo4j";
    static String password = "123456";
    static Driver driver = null;

    static {
        String configStr = Neo4jConfigurationUtil.loadConfigure("configure.json");
        JSONObject json = JSONObject.fromObject(configStr);
        url = json.optString("NEO4J_BOLT", "bolt://localhost");
        username = json.optString("USERNAME", "neo4j");
        password = json.optString("PASSWORD", "123456");
    }

    public NeoDriver() {
        if (driver == null)
            driver = GraphDatabase.driver(
                    url,
                    AuthTokens.basic(username, password),
                    Config.build().withEncryptionLevel(Config.EncryptionLevel.NONE).toConfig());
    }

    //原因：每个session只能用于一个线程内，将session放在此处是为了可以并行化
    public StatementResult query(String cyper) {
        return execute(session -> session.run(cyper));
    }

    public StatementResult query(String cyper, Map<String, Object> params) {
        return execute(session -> session.run(cyper, params));
    }

    public StatementResult query(String cyper, Value value) {
        return execute(session -> session.run(cyper, value));
    }

    public <R> R execute(Function<Session, R> sessionRFunction) {
        try (Session session = driver.session()) {
            return sessionRFunction.apply(session);
        }
    }

    public void executeVoid(Consumer<Session> sessionConsumer) {
        try (Session session = driver.session()) {
            sessionConsumer.accept(session);
        }
    }

    public void close() {
//		driver.close();
//		driver = null;
    }
}
